import axios from 'axios'
import qs from 'qs'

axios.defaults.withCredentials = true
let config = {
  baseUrl: '',
  beforeSuccess: (res, resolve) => {
    resolve(res)
  },
  beforeError: (res, reject) => {
    reject(res)
  }
}

const request = (url, method = 'post', data = {}, axiosConfig, noBase) => {
  return new Promise((resolve, reject) => {
    for (let key of Object.keys(data)) {
      let newUrl = url.replace(new RegExp('\\{' + key + '}', 'g'), data[key])
      if (url !== newUrl) {
        delete data[key]
      }
      url = newUrl
    }
    if (method === 'get') {
      url += `?${qs.stringify(data)}`
    }
    axios({
      method,
      url: noBase ? url : config.baseUrl + url,
      data,
      withCredentials: !noBase,
      ...axiosConfig
    }).then(res => {
      config.beforeSuccess(res, resolve, reject)
    }, res => {
      config.beforeError(res, reject)
    })
  })
}

request.setConfig = (conf = {}) => {
  config = { ...config, ...conf }
}

request.timeOut = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, 2000)
  })
}

export default request
